# coding=UTF-8
__author__ = 'Administrator'
import pandas as pd

from TempleteMethod import *
from getBackgroud import *
from readData import *
from teamconfig import team_short_name

path_sys = 'D:\\WriteBot\\untitled\\'


class Igenerator(object):
    def make_news(self, script):
        raise Exception('子类必须实现该方法')


class RuleGenerator(Igenerator):
    def __init__(self, player_data_guest=None, player_data_host=None):
        self.cur_player_c, self.cur_player_e, self.all_player_c, self.all_player_e, self.id = loadplayer()
        self.load_all_data(player_data_guest, player_data_host)
        self.load_team_info()
        self.team_a = ''  # 客队
        self.team_b = ''  # 主队
        self.gamedescription = ''
        self.quarter1_s = []  # 第一节特殊事件
        self.quarter2_s = []  # 第二节特殊事件
        self.quarter3_s = []  # 第三节特殊事件
        self.quarter4_s = []  # 第四节特殊事件
        self.trend_dict = {}
        self.graph = getInfoFromKnowledgeGraph()

    def load_basic_info(self, script):
        quarter1 = []
        quarter2 = []
        quarter3 = []
        quarter4 = []
        index = 1
        teams = re.search(r'（(.*)）', script[0]).group(1)
        self.team_a = teams.split('-')[0]  # 客队
        self.team_b = teams.split('-')[1]  # 主队
        self.has_ot = False
        for s in script[1:]:
            if s == '1结束':
                index = 2
                continue
            if s == '2结束':
                index = 3
                continue
            if s == '3结束':
                index = 4
                continue
            if index == 1:
                quarter1.append(s)
            if index == 2:
                quarter2.append(s)
            if index == 3:
                quarter3.append(s)
            if index == 4:
                quarter4.append(s)
        return quarter1, quarter2, quarter3, quarter4

    def process_time(self, time):

        '''
        :param time: 不同格式的时间
        :return: 转换成秒之后的时间
        '''
        min = 0
        sec = 0
        if ':' in time:
            min = re.search(r'(\d*):(\d*)', time).group(1)
            sec = re.search(r'(\d*):(\d*)', time).group(2)
            return int(min) * 60 + int(sec)
        elif '分' in time and '秒' in time:
            min = re.search(r'(\d*)分(\d*)秒', time).group(1)
            sec = re.search(r'(\d*)分(\d*)秒', time).group(2)
            return int(min) * 60 + int(sec)
        elif '.' in time and '"' in time:
            min = 0
            sec = re.search(r'(\d*)\.', time).group(1)
            return int(min) * 60 + int(sec)
        elif '.' not in time and '"' in time:
            min = 0
            sec = re.search(r'(\d*)\"', time).group(1)
            return int(min) * 60 + int(sec)
        return int(min) * 60 + int(sec)

    def get_game_description(self, point_event4):

        # TODO 暂时只通过判断结束时刻的比分来得到比赛描述信息，之后可以添加其他判断方法

        if point_event4[-1][0] < 5:
            gamedesc = '十分激烈'
            gametype = 1
        elif point_event4[-1][0] >= 5 and point_event4[-1][0] < 10:
            gamedesc = '焦灼'
            gametype = 2
        else:
            gamedesc = '波澜不惊'
            gametype = 3
        return gamedesc, gametype

    def __get_highest_score_player(self, team, score_event, is_guest=False, quarter=1):
        '''
        #TODO 需要返回单节最高得分事件和每节球员得分情况
        :param team:
        :param score_event:
        :param is_guest:
        :return:
        '''
        d = {}
        for s in score_event:
            if d.has_key(s[1]):
                d[s[1]] += s[4]
            else:
                d[s[1]] = s[4]
        dict_s = sorted(d.iteritems(), key=lambda d: d[1], reverse=True)
        # print(dict_s[0][0] + str(dict_s[0][1]))
        return dict_s, d

    def __get_score_player_total(self, *socre_plyaer):
        '''
        返回每节累积的球员得分情况
        :param socre_plyaer:
        :return:
        '''
        if len(socre_plyaer) != 4:
            raise Exception('参数个数必须为4个')

        socre_plyaer_total1 = {}
        for name, point in socre_plyaer[0].items():
            socre_plyaer_total1[name] = point
        socre_plyaer_total2 = socre_plyaer_total1.copy()
        for name, point in socre_plyaer[1].items():
            if socre_plyaer_total1.has_key(name):
                socre_plyaer_total2[name] = point + socre_plyaer_total1[name]
            else:
                socre_plyaer_total2[name] = point
        socre_plyaer_total3 = socre_plyaer_total2.copy()
        for name, point in socre_plyaer[2].items():
            if socre_plyaer_total2.has_key(name):
                socre_plyaer_total3[name] = point + socre_plyaer_total2[name]
            else:
                socre_plyaer_total3[name] = point
        socre_plyaer_total4 = socre_plyaer_total3.copy()
        for name, point in socre_plyaer[3].items():
            if socre_plyaer_total3.has_key(name):
                socre_plyaer_total4[name] = point + socre_plyaer_total3[name]
            else:
                socre_plyaer_total4[name] = point
        return socre_plyaer_total1, socre_plyaer_total2, socre_plyaer_total3, socre_plyaer_total4

    def __get_quarter_key_info(self, point_event, score_event_a, score_event_b, score_event):
        '''
        得到每一节比赛的关键信息，如最大领先，相应时间和相应事件
        :param point_event:
        :param score_event_a:
        :param score_event_b:
        :return:
        '''
        start_time = point_event[0][1]
        draw_time = None
        end_time = score_event[-1][1]
        a_start = point_event[0][0]
        a_lead = 0
        a_lead_time = None
        a_end = point_event[-1][0]
        b_start = -point_event[0][0]
        b_lead = 0
        b_lead_time = None
        b_end = -point_event[-1][0]

        for p in point_event:
            if p[0] > 0:
                if p[0] > a_lead:
                    a_lead = p[0]
                    a_lead_time = p[1]
            elif p[0] < 0:
                if -p[0] > b_lead:
                    b_lead = -p[0]
                    b_lead_time = p[1]

        if a_lead > 0 and b_lead > 0:
            draw_t = []
            if self.process_time(a_lead_time) > self.process_time(b_lead_time):
                for p in point_event:
                    if p[0] == 0 and self.process_time(p[1]) < self.process_time(a_lead_time) and self.process_time(
                            p[1]) > self.process_time(b_lead_time):
                        draw_t.append(p[1])
                draw_time = draw_t[len(draw_t) / 2]
            else:
                for p in point_event:
                    if p[0] == 0 and self.process_time(p[1]) > self.process_time(a_lead_time) and self.process_time(
                            p[1]) < self.process_time(b_lead_time):
                        draw_t.append(p[1])
                draw_time = draw_t[len(draw_t) / 2]
        if a_lead_time == point_event[0][-1]:
            lead_player_a = ''
            lead_event_a = ''
        if b_lead_time == point_event[0][-1]:
            lead_player_b = ''
            lead_event_b = ''

        for s in score_event_a:
            if s[-1] == a_lead_time:
                lead_event_a = s[3]
                lead_player_a = s[1]
        for s in score_event_b:
            if s[-1] == b_lead_time:
                lead_event_b = s[3]
                lead_player_b = s[1]

        return start_time, draw_time, end_time, a_start, a_lead, a_lead_time, a_end, b_start, b_lead, b_lead_time, b_end, lead_player_a, lead_event_a, lead_player_b, lead_event_b

    def get_quarter_game_trend(self, end_time, a_start, a_lead, a_lead_time, a_end, b_start, b_lead, b_lead_time,
                               b_end):
        # TODO
        if a_lead > 0 and b_lead > 0:
            if self.process_time(a_lead_time) > self.process_time(b_lead_time):
                if a_start == 0:
                    if a_end > 0:
                        trend = 1
                    elif a_end < 0:
                        if b_end < b_lead:
                            trend = 2
                        elif b_end == b_lead:
                            if self.process_time(b_lead_time) > self.process_time(end_time):
                                trend = 3
                            else:
                                trend = 4
                    else:
                        trend = 5


                elif a_start > 0:
                    if a_start == a_lead:
                        if a_end > 0:
                            trend = 22
                        elif a_end == 0:
                            trend = 26
                        else:
                            if b_lead > b_end:
                                trend = 23
                            elif b_lead == b_end:
                                if self.process_time(b_lead_time) > self.process_time(end_time):
                                    trend = 24
                                else:
                                    trend = 25

                    else:
                        if a_end > 0:
                            trend = 17
                        elif a_end == 0:
                            trend = 21
                        else:
                            if b_lead > b_end:
                                trend = 18
                            elif b_lead == b_end:
                                if self.process_time(b_lead_time) > self.process_time(end_time):
                                    trend = 19
                                else:
                                    trend = 20
                else:
                    if a_end > 0:
                        trend = 50
                    elif a_end == 0:
                        trend = 54
                    else:
                        if b_lead > b_end:
                            trend = 51
                        elif b_lead == b_end:
                            if self.process_time(b_lead_time) > self.process_time(end_time):
                                trend = 52
                            else:
                                trend = 53


            else:
                if a_start == 0:
                    if a_end < 0:
                        trend = 9
                    elif a_end > 0:
                        if a_end < a_lead:
                            trend = 6
                        elif a_end == a_lead:
                            if self.process_time(a_lead_time) > self.process_time(end_time):
                                trend = 7
                            else:
                                trend = 8
                    else:
                        trend = 10
                elif a_start > 0:
                    if a_end < 0:
                        trend = 30
                    elif a_end > 0:
                        if a_end < a_lead:
                            trend = 27
                        elif a_end == a_lead:
                            if self.process_time(a_lead_time) > self.process_time(end_time):
                                trend = 28
                            else:
                                trend = 29
                    else:
                        trend = 31
                else:
                    if b_start == b_lead:
                        if a_end < 0:
                            trend = 48
                        elif a_end > 0:
                            if a_end < a_lead:
                                trend = 45
                            elif a_end == a_lead:
                                if self.process_time(a_lead_time) > self.process_time(end_time):
                                    trend = 46
                                else:
                                    trend = 47
                        else:
                            trend = 49
                    else:
                        if a_end < 0:
                            trend = 43
                        elif a_end > 0:
                            if a_end < a_lead:
                                trend = 40
                            elif a_end == a_lead:
                                if self.process_time(a_lead_time) > self.process_time(end_time):
                                    trend = 41
                                else:
                                    trend = 42
                        else:
                            trend = 44
        elif a_lead == 0 and b_lead > 0:
            if a_start == 0:
                if b_end < b_lead:
                    trend = 14
                elif b_end == b_lead:
                    if self.process_time(b_lead_time) > self.process_time(end_time):
                        trend = 16
                    else:
                        trend = 15
            else:
                if b_start == b_lead:
                    trend = 36
                else:
                    if b_end < b_lead:
                        trend = 37
                    elif b_end == b_lead:
                        if self.process_time(b_lead_time) > self.process_time(end_time):
                            trend = 38
                        else:
                            trend = 39
        elif a_lead > 0 and b_lead == 0:
            if a_start == 0:
                if a_end < a_lead:
                    trend = 11
                elif a_end == a_lead:
                    if self.process_time(a_lead_time) > self.process_time(end_time):
                        trend = 13
                    else:
                        trend = 12
            else:
                if a_lead == a_start:
                    trend = 32
                else:
                    if a_lead > a_end:
                        trend = 33
                    elif a_lead == a_end:
                        if self.process_time(a_lead_time) > self.process_time(end_time):
                            trend = 34
                        else:
                            trend = 35
        return trend

    def load_all_data(self, player_data_guest, player_data_host):
        '''
        #TODO 处理总体数据，得到如本场最高分，最高篮板球员，最高助攻，效率值最高等
        :param player_data_guest:
        :param player_data_host:
        :return:
        '''
        self.guest_data = player_data_guest
        self.host_data = player_data_host

    def load_team_info(self):
        path = path_sys + r'team\team'  # 路径暂时写死 ##lynn 添加系统路径
        self.team_info = pd.read_table(path, sep=' ')
        # with open(path) as f:
        #     for line in f:

    def analyze_one_quarter(self, quarter, team_a, team_b):
        # 先独立分析
        '''
        事件分为['得分'，’篮板‘，’失误‘，’犯规‘，’阵容调整‘]
        :param quarter:
        :param teams:
        :return:
        '''
        # team_a=teams.split('-')[0] #客队
        #
        # # print team_a
        #
        # team_b=teams.split('-')[1] #主队
        #
        # # print team_b

        total_event = []
        point_event = []
        point_event_a = []
        point_event_b = []
        score_event_a = []
        score_event_b = []
        score_event = []
        miss_event_a = []
        miss_event_b = []
        miss_event = []
        reb_event_a = []
        reb_event_b = []
        error_event_a = []
        error_event_b = []
        foul_event_a = []
        foul_event_b = []
        adjust_event_a = []
        adjust_event_b = []
        stop_a = []
        stop_b = []
        stop = []
        for q in quarter:
            q = q.strip()
            if len(q.split(',')) == 4:
                event = q.split(',')[2]
                point = q.split(',')[-1]
                point_a = int(q.split(',')[-1].split('-')[0])
                point_b = int(q.split(',')[-1].split('-')[1])
                t = q.split(',')[1]  # 队名，可以直接获取
                time = q.split(',')[0]
                if '阵容调整' in q:
                    # print '阵容调整'
                    if team_a in q:
                        # print 111111
                        adjust_event_a.append((team_a, '阵容调整', event, point, time))
                        point_event_a.append((point_a - point_b, time))
                    if team_b in q:
                        adjust_event_b.append(
                            (team_b, '阵容调整', event, point, time))
                        point_event_b.append((point_a - point_b, time))
                    total_event.append((t, '阵容调整', event, point, time))
                    point_event.append((point_a - point_b, time))
                if '犯规' in q:

                    # print '犯规'
                    if len(event.split(' ')) == 3:
                        f_event = event.split(' ')[-1]
                        player = '-'.join(event.split(' ')[:2])
                        if '.' in player:
                            player.replace('.', '')
                    else:
                        if '投篮犯规' in event:
                            f_event = '投篮犯规'
                            player = event[:event.index('投篮犯规')]
                        if '技术犯规' in event:
                            f_event = '技术犯规'
                            player = t

                    if team_a in q:
                        foul_event_a.append((team_a, player, '犯规', f_event, point, time))
                        point_event_a.append((point_a - point_b, time))
                    if team_b in q:
                        foul_event_b.append(
                            (team_b, '犯规', f_event, point, time))
                        point_event_b.append((point_a - point_b, time))
                    total_event.append((t, '犯规', event, point, time))
                    point_event.append((point_a - point_b, time))
                if '两分' in event or '三分' in event or ('罚球' in event and '罚球区违例' not in event):
                    # print '得分'
                    try:
                        if len(event.split(' ')) == 3:
                            if '罚球' not in event:
                                f_event = event.split(' ')[-1]
                                player = '-'.join(event.split(' ')[:2])
                                if '.' in player:
                                    player.replace('.', '')
                            else:
                                f_event = event.split(' ')[1]
                                index = int(event.split(' ')[-1][-4])
                                player = event.split(' ')[0]
                                if len(player.split('·')) == 2:
                                    player = player.replace('·', '-')

                        elif len(event.split(' ')) == 2:
                            f_event = event.split(' ')[-1]
                            player = event.split(' ')[0]
                            if len(player.split('·')) == 2:
                                player = player.replace('·', '-')
                            # print(player)
                        else:
                            # print event
                            if '罚球' in event:
                                player = '-'.join(event.split(' ')[:2])
                                f_event = event.split(' ')[2]
                                # print event.split(' ')[-1].decode('utf-8')[-2]
                                index = int(event.split(' ')[-1].decode('utf-8')[-2])
                            else:
                                player = '-'.join(event.split(' ')[:2])
                                f_event = event.split(' ')[-1]
                    except Exception as e:
                        # print(e.message)
                        # print(event)
                        # print('########################')
                        continue

                    if team_a in q:

                        if '两分球进' in event:
                            score_event_a.append((team_a, player, '得分', f_event, 2, point, time))
                            score_event.append((team_a, player, '得分', f_event, 2, point, time))
                            total_event.append((t, '得分', event, point, time))

                        if '两分不中' in event:
                            miss_event_a.append((team_a, player, '打铁', f_event, point, time))
                            miss_event.append((team_a, player, '打铁', f_event, point, time))
                            total_event.append((t, '打铁', event, point, time))

                        if '三分球进' in event:
                            score_event_a.append((team_a, player, '得分', f_event, 3, point, time))
                            score_event.append((team_a, player, '得分', f_event, 3, point, time))
                            total_event.append((t, '得分', event, point, time))

                        if '三分不中' in event:
                            miss_event_a.append((team_a, player, '打铁', f_event, 3, point, time))
                            miss_event.append((team_a, player, '打铁', f_event, 3, point, time))
                            total_event.append((t, '打铁', event, point, time))

                        if '罚球命中' in event:
                            score_event_a.append((team_a, player, '得分', f_event, 1, index, point, time))
                            score_event.append((team_a, player, '得分', f_event, 1, index, point, time))
                            total_event.append((t, '得分', event, point, time))

                        if '罚球不中' in event:
                            miss_event_a.append((team_a, player, '打铁', f_event, index, point, time))
                            miss_event.append((team_a, player, '打铁', f_event, index, point, time))
                            total_event.append((t, '打铁', event, point, time))
                            point_event_a.append((point_a - point_b, time))
                        point_event_a.append((point_a - point_b, time))
                        point_event.append((point_a - point_b, time))
                    if team_b in q:
                        if '两分球进' in event:
                            score_event_b.append((team_b, player, '得分', f_event, 2, point, time))
                            score_event.append((team_b, player, '得分', f_event, 2, point, time))
                            total_event.append((t, '得分', event, point, time))

                        if '两分不中' in event:
                            miss_event_b.append((team_b, player, '打铁', f_event, point, time))
                            miss_event.append((team_b, player, '打铁', f_event, point, time))
                            total_event.append((t, '打铁', event, point, time))

                        if '三分球进' in event:
                            score_event_b.append((team_b, player, '得分', f_event, 3, point, time))
                            score_event.append((team_b, player, '得分', f_event, 3, point, time))
                            total_event.append((t, '得分', event, point, time))

                        if '三分不中' in event:
                            miss_event_b.append((team_b, player, '打铁', f_event, 3, point, time))
                            miss_event.append((team_b, player, '打铁', f_event, 3, point, time))
                            total_event.append((t, '打铁', event, point, time))

                        if '罚球命中' in event:
                            score_event_b.append((team_b, player, '得分', f_event, 1, index, point, time))
                            score_event.append((team_b, player, '得分', f_event, 1, index, point, time))
                            total_event.append((t, '得分', event, point, time))

                        if '罚球不中' in event:
                            miss_event_b.append((team_b, player, '打铁', f_event, index, point, time))
                            miss_event.append((team_b, player, '打铁', f_event, index, point, time))
                            total_event.append((t, '打铁', event, point, time))

                        point_event_b.append((point_a - point_b, time))
                        point_event.append((point_a - point_b, time))
                if '篮板球' in event:
                    # print '篮板'
                    if len(event.split(' ')) == 3:
                        f_event = event.split(' ')[-1]
                        player = '-'.join(event.split(' ')[:2])
                        if '.' in player:
                            player.replace('.', '')
                    else:
                        player = event.split(' ')[0]
                        f_event = event.split(' ')[1]

                    if team_a in q:
                        reb_event_a.append((team_a, player, '篮板球', f_event, point, time))
                        point_event_a.append((point_a - point_b, time))
                    if team_b in q:
                        reb_event_b.append((team_b, player, '篮板球', f_event, point, time))
                        point_event_b.append((point_a - point_b, time))
                    point_event.append((point_a - point_b, time))
                    total_event.append((t, '篮板球', event, point, time))
                if '失误' in event:
                    # print '失误'
                    if len(event.split(' ')) == 3:
                        f_event = re.search(r'\((.*)\)', event.split(' ')[-1]).group(1)
                        player = '-'.join(event.split(' ')[:2])
                        if '.' in player:
                            player.replace('.', '')
                    else:
                        player = event.split(' ')[0]
                        f_event = event.split(' ')[1]
                    if team_a in q:
                        error_event_a.append((team_a, player, '失误', f_event, point, time))
                        point_event_a.append((point_a - point_b, time))
                    if team_b in q:
                        error_event_b.append((team_b, player, '失误', f_event, point, time))
                        point_event_b.append((point_a - point_b, time))
                    point_event.append((point_a - point_b, time))
                    total_event.append((t, '失误', event, point, time))
                if '暂停' in event:
                    # print '暂停'
                    try:
                        if team_a in q:
                            stop_a.append((team_a, '暂停', point, time))
                            point_event_a.append((point_a - point_b, time))

                        if team_b in q:
                            stop_b.append((team_b, '暂停', point, time))
                            point_event_b.append(point_event[-1])
                            total_event.append((team_b, '暂停', total_event[-1][-2], total_event[-1][-1]))
                        point_event.append((point_a - point_b, time))
                        total_event.append((t, '暂停', point, time))
                    except:
                        continue
            else:
                if '结束' in q:
                    continue
                if team_a in q:
                    stop_a.append((team_a, '暂停', total_event[-1][-2], total_event[-1][-1]))
                    point_event_a.append(point_event[-1])
                    total_event.append((team_a, '暂停', total_event[-1][-2], total_event[-1][-1]))
                    stop.append((team_a, '暂停', total_event[-1][-2], total_event[-1][-1]))
                if team_b in q:
                    stop_b.append((team_b, '暂停', total_event[-1][-2], total_event[-1][-1]))
                    point_event_b.append(point_event[-1])
                    total_event.append((team_b, '暂停', total_event[-1][-2], total_event[-1][-1]))
                    stop.append((team_a, '暂停', total_event[-1][-2], total_event[-1][-1]))
                point_event.append(point_event[-1])
        return total_event, point_event, point_event_a, point_event_b, score_event_a, score_event_b, score_event, miss_event_a, miss_event_b, miss_event, reb_event_a, reb_event_b, error_event_a, error_event_b, foul_event_a, foul_event_b, adjust_event_a, adjust_event_b, stop_a, stop_b, stop

    def make_quarter1_news(self, trend, quarter_s, team_a, a_lead, lead_player_a, lead_event_a, a_lead_time, team_b,
                           b_lead, lead_player_b, lead_event_b, b_lead_time, highest_score, highest_score_player,
                           score_event_a, score_event_b):
        if trend == 2:
            method2(quarter_s, team_a, a_lead, lead_player_a, lead_event_a, a_lead_time, team_b, b_lead, lead_player_b,
                    lead_event_b, b_lead_time, highest_score, highest_score_player, score_event_a, score_event_b)

    def get_team_comparison(self, gameInfo):
        gtime = gameInfo.split(' ')[0].split('：')[1]
        temp_date = re.findall('([0-9]+)年([0-9]+)月([0-9]+)日', gtime)
        index = temp_date[0][2]
        if int(index) <= 10:
            index = '0' + str(int(index) - 1)
        else:
            index = str(int(index) - 1)
        t = temp_date[0][0] + '-' + temp_date[0][1] + '-' + index
        team_a_performance, team_b_performance = get_team_comparison2(team_short_name[self.team_a],
                                                                      team_short_name[self.team_b],
                                                                      t)
        if int(team_a_performance.split('胜')[0]) > int(team_b_performance.split('胜')[0]):
            better_team = self.team_a + '战绩占优。'
        elif int(team_a_performance.split('胜')[0]) < int(team_b_performance.split('胜')[0]):
            better_team = self.team_b + '战绩占优。'
        else:
            better_team = '双方旗鼓相当。'
        return team_a_performance, team_b_performance, gtime, better_team

    def get_end_text(self, point_event, quarter):
        # TODO 添加更多的结束文本
        if quarter != 4:
            if point_event[-1][0] > 0:
                end = self.team_a + '领先' + self.team_b + str(point_event[-1][0]) + '分。'
            elif point_event[-1][0] < 0:
                end = self.team_b + '领先' + self.team_a + str(-point_event[-1][0]) + '分。'
            else:
                end = '双方战平。'
        else:
            if point_event[-1][0] > 0:
                end = self.team_a + '战胜' + self.team_b + '。'
            elif point_event[-1][0] < 0:
                end = self.team_b + '战胜' + self.team_a + '。'
            else:
                end = '双方战平,进入加时。'
        return end

    def get_key_data(self, point_event, score_event, score_event_a, score_event_b):
        start_time = point_event[0][1]
        draw_time = None
        end_time = score_event[-1][-1]
        a_start = point_event[0][0]
        a_lead = 0
        a_lead_time = None
        a_end = point_event[-1][0]
        b_start = -point_event[0][0]
        b_lead = 0
        b_lead_time = None
        b_end = -point_event[-1][0]
        lead_player_a = ''
        lead_event_a = ''
        lead_player_b = ''
        lead_event_b = ''
        for p in point_event:
            if p[0] > 0:
                if p[0] > a_lead:
                    a_lead = p[0]
                    a_lead_time = p[1]
            elif p[0] < 0:
                if -p[0] > b_lead:
                    b_lead = -p[0]
                    b_lead_time = p[1]
        if a_lead > 0 and b_lead > 0:
            draw_t = []
            reverse_t = []
            pre = 0
            if self.process_time(a_lead_time) > self.process_time(b_lead_time):
                for p in point_event:
                    if self.process_time(p[1]) <= self.process_time(
                            a_lead_time) and self.process_time(p[1]) >= self.process_time(b_lead_time):
                        if pre != 0 and p[0] == 0:
                            draw_t.append(p[1])
                        if pre > 0 and p[0] < 0:
                            reverse_t.append(p[1])
                        pre = p[0]
            else:
                for p in point_event:
                    if self.process_time(p[1]) >= self.process_time(
                            a_lead_time) and self.process_time(p[1]) <= self.process_time(b_lead_time):
                        if pre != 0 and p[0] == 0:
                            draw_t.append(p[1])
                        if pre < 0 and p[0] > 0:
                            reverse_t.append(p[1])
                        pre = p[0]
            if len(draw_t) != 0:
                draw_time = draw_t[len(draw_t) / 2]
            else:
                reverse_time = reverse_t[len(reverse_t) / 2]
        for s in score_event_a:
            if s[-1] == a_lead_time:
                lead_event_a = s[3]
                lead_player_a = s[1]
        for s in score_event_b:
            if s[-1] == b_lead_time:
                lead_event_b = s[3]
                lead_player_b = s[1]
        return start_time, draw_time, end_time, a_start, a_lead, a_lead_time, a_end, b_start, b_lead, b_lead_time, b_end, lead_player_a, lead_event_a, lead_player_b, lead_event_b

    def get_info_from_KG(self):
        # TODO 从知识图谱中获取更多信息
        partition1 = self.graph.getPartition(self.team_a)
        partition2 = self.graph.getPartition(self.team_b)
        temp = ''
        if partition1 == u'东部' and partition2 == u'东部':
            temp = Template.game_description2[2]
        elif partition1 == u'西部' and partition2 == u'西部':
            temp = Template.game_description2[0]
        else:
            temp = Template.game_description2[1]
        s1, s2, tag = self.graph.getLastGame(self.team_a, self.team_b)
        if s1 > s2 and tag == 0:
            win = self.team_b
            lose = self.team_a
        elif s1 < s2 and tag == 0:
            win = self.team_a
            lose = self.team_b
        elif s1 > s2 and tag == 1:
            win = self.team_a
            lose = self.team_b
        else:
            win = self.team_b
            lose = self.team_a
        return win, lose, temp

    def make_news(self, script, gameInfo, label_news):
        try:
            time = gameInfo.split(' ')[0].split('：')[1]
        except Exception:
            time = None
        try:
            arena = gameInfo.split(' ')[3].split('：')[1]
        except:
            arena = None
        try:
            timecost = gameInfo.split(' ')[2].split('：')[1]
        except:
            timecost = None
        quarter1, quarter2, quarter3, quarter4 = self.load_basic_info(script)
        total_event1, point_event1, point_event_a1, point_event_b1, score_event_a1, score_event_b1, score_event1, miss_event_a1, miss_event_b1, miss_event1, reb_event_a1, reb_event_b1, error_event_a1, error_event_b1, foul_event_a1, foul_event_b1, adjust_event_a1, adjust_event_b1, stop_a1, stop_b1, stop1 = self.analyze_one_quarter(
            quarter1, self.team_a, self.team_b)
        total_event2, point_event2, point_event_a2, point_event_b2, score_event_a2, score_event_b2, score_event2, miss_event_a2, miss_event_b2, miss_event2, reb_event_a2, reb_event_b2, error_event_a2, error_event_b2, foul_event_a2, foul_event_b2, adjust_event_a2, adjust_event_b2, stop_a2, stop_b2, stop2 = self.analyze_one_quarter(
            quarter2, self.team_a, self.team_b)
        total_event3, point_event3, point_event_a3, point_event_b3, score_event_a3, score_event_b3, score_event3, miss_event_a3, miss_event_b3, miss_event3, reb_event_a3, reb_event_b3, error_event_a3, error_event_b3, foul_event_a3, foul_event_b3, adjust_event_a3, adjust_event_b3, stop_a3, stop_b3, stop3 = self.analyze_one_quarter(
            quarter3, self.team_a, self.team_b)
        total_event4, point_event4, point_event_a4, point_event_b4, score_event_a4, score_event_b4, score_event4, miss_event_a4, miss_event_b4, miss_event4, reb_event_a4, reb_event_b4, error_event_a4, error_event_b4, foul_event_a4, foul_event_b4, adjust_event_a4, adjust_event_b4, stop_a4, stop_b4, stop4 = self.analyze_one_quarter(
            quarter4, self.team_a, self.team_b)
        # 描述
        gamedesc, gametype = self.get_game_description(point_event4)

        end1 = self.get_end_text(point_event1, 1)
        end2 = self.get_end_text(point_event2, 2)
        end3 = self.get_end_text(point_event3, 3)
        end4 = self.get_end_text(point_event4, 4)

        team_a_performance, team_b_performance, gtime, better_team = self.get_team_comparison(gameInfo)

        # TODO 新闻后缀信息生成
        news_postfix = '\n'.join(label_news.split('###')[2:-1])

        # 关键信息提取
        start_time1, draw_time1, end_time1, a_start1, a_lead1, a_lead_time1, a_end1, b_start1, b_lead1, b_lead_time1, b_end1, lead_player_a1, lead_event_a1, lead_player_b1, lead_event_b1 = self.get_key_data(
            point_event1, score_event1, score_event_a1, score_event_b1)
        start_time2, draw_time2, end_time2, a_start2, a_lead2, a_lead_time2, a_end2, b_start2, b_lead2, b_lead_time2, b_end2, lead_player_a2, lead_event_a2, lead_player_b2, lead_event_b2 = self.get_key_data(
            point_event2, score_event2, score_event_a2, score_event_b2)
        start_time3, draw_time3, end_time3, a_start3, a_lead3, a_lead_time3, a_end3, b_start3, b_lead3, b_lead_time3, b_end3, lead_player_a3, lead_event_a3, lead_player_b3, lead_event_b3 = self.get_key_data(
            point_event3, score_event3, score_event_a3, score_event_b3)
        start_time4, draw_time4, end_time4, a_start4, a_lead4, a_lead_time4, a_end4, b_start4, b_lead4, b_lead_time4, b_end4, lead_player_a4, lead_event_a4, lead_player_b4, lead_event_b4 = self.get_key_data(
            point_event4, score_event4, score_event_a4, score_event_b4)

        trend1 = self.get_quarter_game_trend(end_time1, a_start1, a_lead1, a_lead_time1, a_end1, b_start1, b_lead1,
                                             b_lead_time1, b_end1)
        trend2 = self.get_quarter_game_trend(end_time2, a_start2, a_lead2, a_lead_time2, a_end2, b_start2, b_lead2,
                                             b_lead_time2, b_end2)
        trend3 = self.get_quarter_game_trend(end_time3, a_start3, a_lead3, a_lead_time3, a_end3, b_start3, b_lead3,
                                             b_lead_time3, b_end3)
        trend4 = self.get_quarter_game_trend(end_time4, a_start4, a_lead4, a_lead_time4, a_end4, b_start4, b_lead4,
                                             b_lead_time4, b_end4)

        self.trend_dict['quarter1'] = trend1
        self.trend_dict['quarter2'] = trend2
        self.trend_dict['quarter3'] = trend3
        self.trend_dict['quarter4'] = trend4

        func_dict[trend1](self.quarter1_s, self.team_a, a_start1, a_lead1, lead_player_a1, lead_event_a1, a_lead_time1,
                          self.team_b,
                          b_start1, b_lead1, lead_player_b1, lead_event_b1, b_lead_time1, score_event1, score_event_a1,
                          score_event_b1, a_end1, b_end1)
        func_dict[trend2](self.quarter2_s, self.team_a, a_start2, a_lead2, lead_player_a2, lead_event_a2, a_lead_time2,
                          self.team_b,
                          b_start2,
                          b_lead2, lead_player_b2, lead_event_b2, b_lead_time2, score_event2, score_event_a2,
                          score_event_b2,
                          a_end2, b_end2)
        func_dict[trend3](self.quarter3_s, self.team_a, a_start3, a_lead3, lead_player_a3, lead_event_a3, a_lead_time3,
                          self.team_b,
                          b_start3,
                          b_lead3, lead_player_b3, lead_event_b3, b_lead_time3, score_event3, score_event_a3,
                          score_event_b3,
                          a_end3, b_end3)
        func_dict[trend4](self.quarter4_s, self.team_a, a_start4, a_lead4, lead_player_a4, lead_event_a4, a_lead_time4,
                          self.team_b,
                          b_start4,
                          b_lead4, lead_player_b4, lead_event_b4, b_lead_time4, score_event4, score_event_a4,
                          score_event_b4,
                          a_end4, b_end4)

        win, lose, temp = self.get_info_from_KG()

        news = Template.START.replace('#time', gtime).replace('#f_start1',
                                                              random.choice(Template.f_start1).replace('#主队',
                                                                                                       self.team_b).replace(
                                                                  '#客队', self.team_a)) + \
               temp + \
               Template.game_description.replace('#比赛描述', gamedesc) + \
               Template.host_team_description.replace('#主队', self.team_b).replace('#战绩1', team_b_performance) + ',' + \
               Template.guest_team_description.replace('#客队', self.team_a).replace('#战绩2', team_a_performance) + \
               better_team + \
               random.choice(Template.last_match).replace('#球队1', win).replace('#球队2', lose) + \
               random.choice(Template.quarter1_start) + \
               self.quarter1_s[0] + Template.quarter1_end.replace('#结果1', end1) + random.choice(
            Template.quarter2_start) + \
               self.quarter2_s[0] + Template.quarter2_end.replace('#结果2', end2) + random.choice(
            Template.quarter3_start) + \
               self.quarter3_s[0] + Template.quarter3_end.replace('#结果3', end3) + random.choice(
            Template.quarter4_start) + \
               self.quarter4_s[0] + Template.quarter4_end.replace('#结果4', end4) + news_postfix
        return news

    def run(self, id=156240):
        gameInfo, script, player_data_guest, player_data_host, label_news = loadtextlive(id)
        news = self.make_news(script, gameInfo, label_news)
        # print(news)

    def make_txt_file(self, news_id, news, txt_path):
        save_path = os.path.join(txt_path, "article_" + str(news_id) + '.txt')
        with open(save_path, "w", encoding="utf-8") as f:
            f.write(news)
            f.flush()


if __name__ == '__main__':
    rg = RuleGenerator()
    rg.run()
